<template>
  <div class="sys-page">
    <!--   自动控制熄灯   -->
    <div class="lamp-btn-box">
      <div class="lamp-btn" v-for="(item,idx) in lampData"
           @click="lampHandle(item,idx)"
           :class="{'on': lampIdx == idx}">
        {{ item.towername || item.brigename }}
      </div>
    </div>
    <div style="height: calc(100% - 61px)">
      <base-table :pagination="pagination">
        <el-table :data="tableData" stripe border
                  :cell-style="{ textAlign: 'center' }"
                  :header-cell-style="{ textAlign: 'center' }"
                  header-row-class-name="headerRow"
                  @selection-change="handleSelectionChange"
                  class="lamp-table"
                  style="width: 100%">
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" width="150" label="序号" #default="scope">
            {{ scope.$index < 9 ? '0' + (scope.$index + 1) : scope.$index + 1 }}
          </el-table-column>
          <el-table-column prop="lightnameFact" label="编号"/>
          <el-table-column prop="lightStatus" label="当前状态" #default="scope">
            {{ scope.row.lightStatus == 1 ? '开启' : '关闭' }}
          </el-table-column>
          <el-table-column prop="manual" label="灯具方向" #default="scope">
            <template v-if="scope.row.manual == 1">东</template>
            <template v-else-if="scope.row.manual == 2">南</template>
            <template v-else-if="scope.row.manual == 3">西</template>
            <template v-else-if="scope.row.manual == 4">北</template>
          </el-table-column>
          <el-table-column label="操作">
            <el-table-column prop="lamp">
              <template #header>
                <span @click="switchOpenClose(true)" style="cursor: pointer">点击执行</span>
              </template>
              <el-table-column prop="state">
                <template #header>
                  <span @click="switchHandle(true)" style="cursor: pointer">开启</span>
                </template>
                <template #default="scope">
                  <el-checkbox :disabled="scope.row.maintenanceFlag || scope.row.flag"
                               v-model="scope.row.switchFlag"
                               @change="switchLampHandle(scope.row.switchFlag,scope.row,'open')"  label="开启"/>
                </template>
              </el-table-column>
              <el-table-column prop="state">
                <template #header>
                  <span @click="switchHandle(false)" style="cursor: pointer">关闭</span>
                </template>
                <template #default="scope">
                  <el-checkbox :disabled="scope.row.switchFlag || scope.row.flag"
                               v-model="scope.row.maintenanceFlag"
                               @change="switchLampHandle(scope.row.maintenanceFlag,scope.row,'close')" label="关闭"/>
                </template>
              </el-table-column>
            </el-table-column>

          </el-table-column>
        </el-table>
      </base-table>
    </div>
  </div>

</template>

<script>
import BaseTable from "../../components/baseTable.vue";
import {
  BrigeZongLan,
  judgeLightOnline,
  refreshGatewayData,
  sendCommandLightMsg,
  TowerZongLan, updateLightType
} from "../../router/api.js";
import {mapGetters} from "vuex";

export default {
  name: "controlLightsOff",
  computed: {
    ...mapGetters(['currentNav','userInfo','refreshFlag'])
  },
  components: {BaseTable},
  data() {
    return {
      lampBtn: [],
      lampIdx: 0,
      pagination: {
        pages: 1,
        pageSize: 18,
        total: 0,
      },
      tableData: [],
      lampData: [],
      selLamp: [],
      is: false,
      fetchingFlag: true,
    }
  },
  watch:{
    'currentNav': {
      deep: true,
      handler(){
        this.lampIdx = 0;
        this.selLamp = [];
        this.getLampData()
      }
    },
    'refreshFlag': {
      deep: true,
      handler(n) {
        if(n) {
          this.getLampData();
          refreshGatewayData();
          // judgeLightOnline();

          this.$store.commit('SET_WAIT', true)
        }
      }
    }
  },
  beforeRouteLeave(to, from, next) {
    clearInterval(this.timer);
    this.timer = null;
    this.fetchingFlag = false;

    next();
  },
  created() {
    this.getLampData();

    this.timer = setInterval(() => {
      if(this.fetchingFlag){
        this.getLampData();
      }
    }, 1000 * 5)
  },
  methods: {
    async getLampData() {
      this.fetchingFlag = true;
      // this.bridgeClass = [];
      // this.mappingList = [];

      let resLamp = await TowerZongLan();
      let resLampBridge = await BrigeZongLan()
      let lighthouse = [], lampBridge = [];
      if (resLamp.data.code == 200) {
        lighthouse = JSON.parse(JSON.stringify(resLamp.data.data)).filter(opt => opt.towerArea == this.currentNav+1);
      }else{
        this.$message.warning('无法请求服务器资源，请确认服务器是否开启')
      }
      if (resLampBridge.data.code == 200) {
        lampBridge = JSON.parse(JSON.stringify(resLampBridge.data.data)).filter(opt => opt.brigeArea == this.currentNav+1);
      }

      this.lampData = lighthouse;
      if (this.lampData.length >= 3) {
        this.lampData.splice(3, 0, ...lampBridge)
      } else {
        this.lampData.push(...lampBridge)
      }
      this.lampData.forEach(opt => {
        opt['scene'] = opt.switchList.filter(o => o.type == 1);
      })

      let arr = this.lampData[this.lampIdx].lightList.filter(o => o.lightType == 1);
      //判断是否有现场
      let flagScene = this.lampData[this.lampIdx].scene.some(o => o.status == 0);
      //手动才可以编辑，自动不可编辑 manual：0（自动）1（手动）

      if(this.selLamp.length){
        if(this.lampData[this.lampIdx].towername){
          //灯塔
          if(this.selLamp[0].lamp == 'all'){
            //全选
            arr.forEach((opt,idx) => {
              let name = opt.lightnameFact;
              let commandMegStr = this.selLamp[0].commandMegStr;
              if(commandMegStr[name] !== undefined){
                if(this.selLamp[0].action == 1){
                  opt['switchFlag'] = true;
                  opt['maintenanceFlag'] = false;
                }else{
                  opt['switchFlag'] = false;
                  opt['maintenanceFlag'] = true;
                }
              }else{
                opt['switchFlag'] = false;
                opt['maintenanceFlag'] = false;
              }
            })
          }else{
            //单选
            arr.forEach((opt,idx) => {
              let v = this.selLamp.find(o => o.lamp == opt.lightnameFact);
              if(v && Object.keys(v).length){
                if(v.action == 1){
                  opt['switchFlag'] = true;
                  opt['maintenanceFlag'] = false;
                }else{
                  opt['switchFlag'] = false;
                  opt['maintenanceFlag'] = true;
                }
              }
            })
          }
        }else{
          //灯桥
          if(this.selLamp[0].lamp == 'all'){
            //全选
            let megStr = {};
            this.selLamp.forEach(opt => {
              megStr = {...megStr,...opt.commandMegStr}
            })
            arr.forEach((opt,idx) => {
              let name = opt.lightnameFact;
              if(megStr[name] !== undefined){
                if(this.selLamp[0].action == 1){
                  opt['switchFlag'] = true;
                  opt['maintenanceFlag'] = false;
                }else{
                  opt['switchFlag'] = false;
                  opt['maintenanceFlag'] = true;
                }
              }else{
                opt['switchFlag'] = false;
                opt['maintenanceFlag'] = false;
              }
            })
          }else{
            //单选
            arr.forEach((opt,idx) => {
              let v = this.selLamp.find(o => o.lamp == opt.lightnameFact);
              if(v && Object.keys(v).length){
                if(v.action == 1){
                  opt['switchFlag'] = true;
                  opt['maintenanceFlag'] = false;
                }else{
                  opt['switchFlag'] = false;
                  opt['maintenanceFlag'] = true;
                }
              }
            })
          }
        }
      }else{
        arr.forEach((opt,idx) => {
          opt['switchFlag'] = false;
          opt['maintenanceFlag'] = false;
        })
      }

      arr.forEach((opt,idx) => {
        if(flagScene || opt.manual == 0){
          opt['flag'] = true;
        }else{
          opt['flag'] = false;
        }
      })
      this.tableData = arr;

      // let lampNameArr = [];
      // this.lampData.forEach(opt => {
      //   let name = opt.towername || opt.brigename;
      //   lampNameArr.push({
      //     name,
      //     status: opt.manual,
      //     gatewaylist: opt.gatewaylist,
      //     switchList: opt.switchList
      //   })
      //
      //   opt['scene'] = opt.switchList.filter(o => o.type == 1);
      //
      //   this.mappingList[name] = [];
      //   let tmp = opt.lightList.filter(o => o.lightType == 5);
      //   this.mappingList[name] = tmp;
      // })
      // console.log('this.lampData',this.lampData,this.tableData)
      // this.lampName = lampNameArr;
      // this.viewLamp();

      this.$store.commit('SET_REFRESHFLAG', false)
    },
    lampHandle(item, idx) {
      this.selLamp = [];
      let arr = this.lampData[idx].lightList.filter(o => o.lightType == 1);
      //判断是否有现场
      let flagScene = this.lampData[idx].scene.some(o => o.status == 0);
      //手动才可以编辑，自动不可编辑 manual：0（自动）1（手动）

      arr.forEach(opt => {
        opt['switchFlag'] = false;
        opt['maintenanceFlag'] = false;
        if(flagScene || opt.manual == 0){
          opt['flag'] = true;
        }else{
          opt['flag'] = false;
        }
      })
      this.tableData = arr
      this.lampIdx = idx;
    },
    switchHandle(val) {
      let data = this.lampData[this.lampIdx]
      let gatewayName = '', topic = '', lamp = '';
      let action = val ? 1 : 0;;
      let commandMegStr = {};

      let arr = data.lightList.filter(o => o.lightType == 1);
      if(val){
        this.tableData.forEach(opt => {
          opt['switchFlag'] = true;
          opt['maintenanceFlag'] = false;
        })
      }else{
        this.tableData.forEach(opt => {
          opt['switchFlag'] = false;
          opt['maintenanceFlag'] = true;
        })
      }

      arr.forEach(o => {
        let _lightnameFact = null;
        if (o.lightnameFact) _lightnameFact = o.lightnameFact;
        commandMegStr[_lightnameFact] = action;
      })

      if(data.towername) {
        //灯塔
        let tmp = []
        gatewayName = data.gatewaylist.gatewayName;
        topic = data.gatewaylist.subTopic;
        lamp = 'all';

        tmp.push({
          gatewayName,
          topic,
          lamp,
          action,
          commandMegStr
        })

        this.selLamp = tmp;
        /*this.lightMsgHandle({
          gatewayName,
          topic,
          lamp,
          action,
          commandMegStr
        })*/
      }else{
        //灯桥
        let tmp = []
        let bridgeGatewaylistData = this.setBridgeData();
        for(let i = 0; i < bridgeGatewaylistData.length; i++){
          commandMegStr = {};
          let o = bridgeGatewaylistData[i];
          gatewayName = o.gatewayName;
          topic = o.subTopic;
          lamp = 'all'
          o.lightList.forEach(v => {
            commandMegStr[v.lightnameFact] = action;
          })
          tmp.push({
            gatewayName,
            topic,
            lamp,
            action,
            commandMegStr
          })
          /*this.lightMsgHandle({
            gatewayName,
            topic,
            lamp,
            action,
            commandMegStr
          })*/
        }
        this.selLamp = tmp;
      }
    },
    async switchLampHandle(val, row, str){
      let data = this.lampData[this.lampIdx]
      let gatewayName = '', topic = '', lamp = '';
      // let action = val ? 1 : 0;
      let action = str == 'open' ? 1 : 0;
      let commandMegStr = {};
      if(data.towername){
        //灯塔
        gatewayName = data.gatewaylist.gatewayName;
        topic = data.gatewaylist.subTopic;
        lamp = row.lightnameFact;
        commandMegStr[lamp] = action;
      }else{
        //灯桥
        let val = data.gatewaylist.find(o => o.gatewayId == row.gatewayId);
        gatewayName = val.gatewayName;
        topic = val.subTopic;
        lamp = row.lightnameFact;
        commandMegStr[lamp] = action;
      }
      if(val){
        this.selLamp.push({
          gatewayName,
          topic,
          lamp,
          action,
          commandMegStr,
          str,
          lightId: row.lightId
        })
      }else{
        if(this.selLamp[0].lamp == 'all'){
          //全选
          this.selLamp.forEach(opt => {
            if(opt.commandMegStr[lamp] !== undefined){
              delete opt.commandMegStr[lamp]
            }
          })
        }else{
          let _i = this.selLamp.findIndex(opt => opt.lamp == lamp);
          this.selLamp.splice(_i,1)
        }
      }

      /*this.lightMsgHandle({
        gatewayName,
        topic,
        lamp,
        action,
        commandMegStr
      })*/
    },
    lightMsgHandle(params){
      sendCommandLightMsg(params).then(res => {
        if (res.data.code == 200) {
          this.selLamp = []
          this.getLampData();
          // this.$message.success(res.data.msg);
        } else {
          // this.$message.warning(res.data.msg);
        }
      })
    },
    setBridgeData(){
      let arr = JSON.parse(JSON.stringify(this.tableData));
      let gatewaylist = JSON.parse(JSON.stringify(this.lampData[this.lampIdx].gatewaylist));
      arr.forEach(opt => {
        let val = gatewaylist.find(o => o.gatewayId == opt.gatewayId);
        if(!val['lightList']){
          val['lightList'] = []
        }
        val['lightList'].push(opt);
      })
      return gatewaylist
    },
    maintenanceHandle(val,row) {
      let data = this.lampData[this.lampIdx];
      let topic = '';
      if(data.towername) {
        //灯塔
        topic = data.gatewaylist.subTopic;
      }else{
        //灯桥
        let val = data.gatewaylist.find(o => o.gatewayId == row.gatewayId);
        topic = val.subTopic;
      }
      /*updateLightType({
        CCID: row.ccid,
        topic,
        lightnameFact: row.lightnameFact,
        newLightType: 4
      }).then(res => {
        if (res.data.code == 200) {
          this.getLampData();
          this.$message.success(res.data.msg);
        } else {
          this.$message.warning(res.data.msg);
        }
      })*/
    },
    switchOpenClose(){
      if(!this.selLamp.length) return;
      let open = this.selLamp.every(opt => opt.action == 1);
      let close = this.selLamp.every(opt => opt.action == 0);
      let action = 0, lamp = 'all';
      if(!open && !close){
        action = 3;
        lamp = 'mul'
      }else if(open && !close){
        action = 1
        lamp = 'all'
      }else if(!open && close){
        action = 0
        lamp = 'all'
      }
      let megStrAll = [];
      let megStr = {};
      this.selLamp.forEach(opt => {
        if(!megStr[opt.topic]){
          megStr[opt.topic] = []
        }
        megStr[opt.topic].push(opt)
      })
      let megStrVal = Object.values(megStr);
      megStrVal.forEach(item => {
        let str = {};
        item.forEach(opt => {
          str = {...str, ...opt.commandMegStr}
        })
        megStrAll.push({
          gatewayName: item[0].gatewayName,
          topic: item[0].topic,
          lamp: item[0].lamp,
          action,
          commandMegStr: str
        });
      })
      megStrAll.forEach(opt => {
        let {gatewayName,topic,lamp,action, commandMegStr} = opt;
        this.lightMsgHandle({
          gatewayName,
          topic,
          lamp,
          action,
          commandMegStr
        })
      })

    },
    handleSelectionChange(val){
      console.log(val)
    }
  }
}
</script>

<style scop lang="scss">
.lamp-btn-box {
  display: flex;
  margin: 12px auto 17px;

  .lamp-btn {
    width: 104px;
    height: 42px;
    line-height: 42px;
    text-align: center;
    color: #336666;
    font-size: 16px;
    font-weight: 400;
    margin-right: 2px;
    background: url("@/assets/images/img-area-bg-def.svg") no-repeat left top;
    background-size: 100% 100%;
    cursor: pointer;

    &:hover, &.on {
      background: url("@/assets/images/img-area-bg.svg") no-repeat left top;
      background-size: 100% 100%;
    }
  }
}

.sys-page {
  margin-left: 10px;
  height: 100%;

  .lamp-table {
    height: calc(100% - 29px);
  }
}

</style>
<style>
.headerRow {
  background: linear-gradient(to right, #6B92F0, #76D0FF) !important;
}

.el-table th.el-table__cell {
  background-color: transparent;
  color: #fff;
}

.el-table thead.is-group th.el-table__cell {
  background-color: transparent;
  color: #fff;
}
</style>
